package cn.bdqn.layui.service.rabbit;

import cn.bdqn.layui.entity.vo.ProUserVo;
import cn.bdqn.layui.mapper.ProductSuccessMapper;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class RabbitSenderService {

    @Resource
    RabbitTemplate rabbitTemplate;

    @Resource
    ProductSuccessMapper productSuccessMapper;

    public void sendProductSuccessEmailMsg(String orderNo) {
        //todo:根据订单号查询信息
        ProUserVo proUserVo = productSuccessMapper.findByCode(orderNo);
        rabbitTemplate.convertAndSend("email.exchange", "email.routing.key", proUserVo);
    }

    //秒杀成功后生成抢购订单 - 发送信息到死信队列-超时未支付的
    public void sendKillSuccessOrderExpireMsg(String odedrCode) {
        ProUserVo proUserVo = productSuccessMapper.findByCode(odedrCode);
        if(proUserVo != null){
            rabbitTemplate.convertAndSend("kill.dead.prod.exchange", "kill.dead.prod.routing.key", proUserVo, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    MessageProperties mq = message.getMessageProperties();
                    mq.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    mq.setHeader(AbstractJavaTypeMapper.DEFAULT_KEY_CLASSID_FIELD_NAME, ProUserVo.class);
                    //todo:动态设置ttl
                    Long ttl = 1800000L;
                    mq.setExpiration(String.valueOf(ttl));
                    return message;
                }
            });
        }

    }

}
